package com.gjd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gjd.domain.ResponseResult;
import com.gjd.domain.entity.Category;
import com.gjd.domain.entity.ServerCondition;
import com.gjd.domain.entity.User;
import com.gjd.mapper.CategoryMapper;
import com.gjd.mapper.UserMapper;
import com.gjd.service.ServerConditionService;
import com.gjd.mapper.ServerConditionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yang'shun'tao
 * @description 针对表【server_condition】的数据库操作Service实现
 * @createDate 2023-01-15 10:07:08
 */
@Service
public class ServerConditionServiceImpl extends ServiceImpl<ServerConditionMapper, ServerCondition>
        implements ServerConditionService {

    @Autowired
    ServerConditionMapper serverConditionMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    public ResponseResult refineCondition(ServerCondition serverCondition) {
        Integer serverId = serverCondition.getServerId();
        LambdaQueryWrapper<ServerCondition> serverConditionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        serverConditionLambdaQueryWrapper.eq(ServerCondition::getServerId, serverId);
        categoryLambdaQueryWrapper.eq(Category::getId,serverCondition.getCategoryId());
        userLambdaQueryWrapper.eq(User::getId,serverCondition.getServerId());

        String categoryName = categoryMapper.selectOne(categoryLambdaQueryWrapper).getName();
        Long categoryId = categoryMapper.selectOne(categoryLambdaQueryWrapper).getId();
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        user.setCategoryName(categoryName);
        user.setCategoryId(categoryId);
        userMapper.updateById(user);

        if ( serverConditionMapper.selectCount(serverConditionLambdaQueryWrapper) == 0) {
            serverCondition.setStatus(4);
            serverConditionMapper.insert(serverCondition);
        } else {
            serverConditionMapper.update(serverCondition, serverConditionLambdaQueryWrapper);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getCondition(Long serverId) {
        LambdaQueryWrapper<ServerCondition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ServerCondition::getServerId,serverId);
        ServerCondition serverCondition = serverConditionMapper.selectOne(queryWrapper);
        return ResponseResult.okResult(serverCondition);
    }
}




